<?php

require_once 'core/model/table/row/layout.php';

class Core_Model_Table_Layout extends Model_Table
{

    protected $_name = 'core_layouts';

    protected $_rowClass = 'Core_Model_Table_Row_Layout';

    /**
     * @param array $rows
     * @return array with structure.
     */
    public function prepareElements($rows)
    {
        $i = 0;
        $maps = array();

        /**
         * remove type layout from rows
         */
        $layout = array();
        $areas = array();

        foreach ($rows as $row)
        {
            $maps[$row['id']] = $row;
        }

        unset($rows);

        foreach ($maps as $index => $row)
        {
            if ('layout' == $row['type'])
            {
                $layout = $this -> prepareElement($row);
                unset($maps[$index]);
            }
        }

        $nest = array(
            'block' => array(
                'block',
                'list',
                'area'
            ),
            'list' => array(
                'list',
                'area'
            ),
        );

        /**
         * layout contain area
         * area contain /list/block
         * list contain list/block
         * block contain block
         */
        foreach ($nest as $type => $parentTypes)
        {
            foreach ($parentTypes as $parentType)
            {
                foreach ($maps as $index => $row)
                {
                    if ($type == $row['type'])
                    {
                        $pid = $row['parent_id'];
                        if (isset($maps[$pid]) && isset($maps[$pid]['type']) && $parentType == $maps[$pid]['type'])
                        {
                            $maps[$pid]['children'][] = $this -> prepareElement($row);
                            unset($maps[$index]);
                            // remote from maps.
                        }
                    }
                }
            }
        }

        foreach ($maps as $index => $row)
        {
            if ('area' == $row['type'])
            {
                $name = $row['name'];
                $areas[$name] = $this -> prepareElement($row);
            }
        }
        // unset all maps.
        unset($maps);

        return array(
            $layout,
            $areas
        );
    }

    public function prepareElement($row)
    {
        if (!isset($row['children']))
        {
            $row['children'] = array();
        }
        return $row;
    }

    public function getAvailableActionList($actionId)
    {
        $result = array($actionId);
        $arr = preg_split('#\W#', $actionId);
        $m_first = array_shift($arr);
        $m_mid = $arr[0];
        $m_end = array_pop($arr);
        $m_remain = implode('.', $arr);

        $result[] = sprintf('%s@%s', $m_first, $m_remain);
        $result[] = sprintf('%s@%s', $m_first, $m_mid);
        $result[] = sprintf('core@%s', $m_remain);
        $result[] = sprintf('core@%s', $m_mid);
        $result[] = 'core@';
        $result = array_unique($result);
        return $result;
    }

    public function loadLayout($section, $actionId, $siteId)
    {
        $actionList = $this -> getAvailableActionList($actionId);

        // echo sprintf("get layout match [%s]", implode(';', $actionList));

        $select = $this -> select() -> where('section=?', $section) -> where('action_id IN (?)', $actionList) -> order('action_id desc');

        /**
         * get layout.
         */
        $layouts = $this -> fetchAll($select);

        if (count($layouts) == 0)
        {
            if (STAGE == 'development')
            {
                throw new Exception(sprintf("no layout match [%s]", implode(';', $actionList)));
            }

            return array(
                null,
                null,
            );

        }

        $layoutId = $layouts[0] -> layout_id;

        unset($layouts);

        $table = Nuo::getTable('core@layout.element');

        $select = $table -> select() -> where('layout_id=?', $layoutId) -> where('enabled=?', 1) -> order('priority ASC');

        $layout = $this -> prepareElements($table -> fetchAll($select) -> toArray());

        return $layout;
    }

    /**
     * get area
     * get all area mode
     */
    public function getAreaAsOptions()
    {
        $table = Nuo::getTable('core@layout.area');

        $ret = array();

        foreach ($table->fetchAll() as $row)
        {
            $ret[$row -> area] = $row -> title;
        }
        return $ret;
    }

    /**
     * get area
     * get all area mode
     */
    public function getAllowAsOptions($area)
    {
        $table = Nuo::getTable('core@layout.allow');
        $select = $table -> select() -> where('area=?', (string)$area);
        $ret = array();

        foreach ($table->fetchAll() as $row)
        {
            $ret[$row -> area] = $row -> name;
        }
        return $ret;
    }

}
